package com.htu.courseService.websocket.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

import java.util.Date;

/**
 * Created By JNNarrator on 2025/01/20 16:08
 * email: jiangn09@chinatelecom.cn
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class SocketMsg<T> {
	private String authToken;
	private Integer code;
	private String app;
	private String operation;
	private T data;
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
	private Date timestamp = new Date();
	public static <T> SocketMsg<T> build(SocketEnumInterface operationEnum,T data){
		SocketMsg<T> socketMsg = new SocketMsg<>();
		socketMsg.setOperation(operationEnum.operation());
		socketMsg.setData(data);
		socketMsg.setApp(operationEnum.app());
		socketMsg.setCode(operationEnum.code());
		return socketMsg;
	}
	public static <T> SocketMsg<T> build(SocketEnumInterface operationEnum){
		SocketMsg<T> socketMsg = new SocketMsg<>();
		socketMsg.setOperation(operationEnum.operation());
		socketMsg.setApp(operationEnum.app());
		socketMsg.setCode(operationEnum.code());
		return socketMsg;
	}
	public static <T> String buildJSON (SocketEnumInterface operationEnum,T data){
		SocketMsg<T> socketMsg = new SocketMsg<>();
		socketMsg.setOperation(operationEnum.operation());
		socketMsg.setData(data);
		socketMsg.setApp(operationEnum.app());
		socketMsg.setCode(operationEnum.code());
		return JSON.toJSONStringWithDateFormat(socketMsg, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat);
	}
	public static String buildJSON (SocketEnumInterface operationEnum){
		SocketMsg<?> socketMsg = new SocketMsg<>();
		socketMsg.setOperation(operationEnum.operation());
		socketMsg.setApp(operationEnum.app());
		socketMsg.setCode(operationEnum.code());
		return JSON.toJSONStringWithDateFormat(socketMsg, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat);
	}
	public static <T> SocketMsg<T> parse(String json, TypeReference<SocketMsg<T>> typeReference){
		return JSON.parseObject(json,typeReference);
	}
	@SuppressWarnings("unchecked")
	public static <T> SocketMsg<T> parse(String json, Class<T> clazz){
		SocketMsg<T> socketMsg = JSON.parseObject(json, SocketMsg.class);
		if (socketMsg.getData().getClass().equals(clazz)){
			return socketMsg;
		}
		return null;
	}
	public static SocketMsg<?> parse(String json){
		return JSON.parseObject(json,SocketMsg.class);
	}
	public String toJSON(){
		return JSON.toJSONStringWithDateFormat(this,"yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat);
	}
}
